package com.intelligencesoft.pss.controller;

import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

import net.sf.json.JSONObject;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.intelligencesoft.pss.auth.LoginUtil;
import com.intelligencesoft.pss.entity.base.PageBean;
import com.intelligencesoft.pss.entity.base.SysMenu;
import com.intelligencesoft.pss.entity.base.UserInfo;
import com.intelligencesoft.pss.entity.binding.BindingList;
import com.intelligencesoft.pss.entity.binding.UserBinding;
import com.intelligencesoft.pss.entity.publish.PublishInfo;
import com.intelligencesoft.pss.enums.BindingType;
import com.intelligencesoft.pss.service.PublishInfoService;
import com.intelligencesoft.pss.service.SysMenuService;
import com.intelligencesoft.pss.service.binding.BindingListService;
import com.intelligencesoft.pss.service.binding.UserBindingService;
import com.intelligencesoft.pss.sina.weibo.weibo4j.Friendships;
import com.intelligencesoft.pss.sina.weibo.weibo4j.Oauth;
import com.intelligencesoft.pss.sina.weibo.weibo4j.Timeline;
import com.intelligencesoft.pss.sina.weibo.weibo4j.Users;
import com.intelligencesoft.pss.sina.weibo.weibo4j.examples.oauth2.Log;
import com.intelligencesoft.pss.sina.weibo.weibo4j.http.AccessToken;
import com.intelligencesoft.pss.sina.weibo.weibo4j.model.Status;
import com.intelligencesoft.pss.sina.weibo.weibo4j.model.User;
import com.intelligencesoft.pss.sina.weibo.weibo4j.model.UserWapper;
import com.intelligencesoft.pss.sina.weibo.weibo4j.model.WeiboException;
import com.intelligencesoft.pss.tencent.weibo.api.FriendsAPI;
import com.intelligencesoft.pss.tencent.weibo.api.UserAPI;
import com.intelligencesoft.pss.tencent.weibo.oauthv2.OAuthV2;
import com.intelligencesoft.pss.tencent.weibo.oauthv2.OAuthV2Client;
import com.intelligencesoft.pss.vo.TencentUserInfoVo;

@Controller
@RequestMapping(value="/home")
public class HomePageController {
	
	@Autowired
	@Qualifier("configProperties")
	private Properties properties;

	@Autowired
	private LoginUtil loginUtil;
	
	@Autowired
	private BindingListService bindingListService;
	
	@Autowired
	private SysMenuService sysMenuService;
	
	@Autowired
	private UserBindingService userBindingService;
	
	@Autowired
	private PublishInfoService publishInfoService;
	
	@Autowired
	private Oauth oauth;
	
	@Autowired
	private Users users;
	
	@Autowired
	private Friendships friendships;
	
	/**
	 * 首页
	 * @author 黄莹璐
	 * @date: 2014-9-7-上午12:12:55
	 * //TODO  黄莹璐编辑
	 * @return
	 * @throws WeiboException
	 */
	@RequestMapping(value="/index",method=RequestMethod.GET)
	public ModelAndView index() throws WeiboException{
		UserInfo loginUser = loginUtil.getLoginUser();
		ModelAndView m = new ModelAndView();
		m.getModelMap().put("user", loginUser);
		m.setViewName("/home/index");
		return m;
	}
	
	/**
	 * 绑定列表页面
	 * @author 黄莹璐
	 * @date: 2014-9-7-上午12:13:03
	 * //TODO  黄莹璐编辑
	 * @return
	 */
	@RequestMapping(value="/showBindingList",method=RequestMethod.GET)
	public ModelAndView showBindingList(){
		ModelAndView m = new ModelAndView();
		List<BindingList> bindings = bindingListService.loadBindingList();
		m.getModelMap().put("bindings", bindings);
		m.setViewName("/bind/show_bind_list");
		return m;
	}
	
	/**
	 * 发布页面
	 * @author 黄莹璐
	 * @date: 2014-9-7-上午12:13:13
	 * //TODO  黄莹璐编辑
	 * @return
	 */
	@RequestMapping(value="/publish",method=RequestMethod.GET)
	public ModelAndView publish(){
		UserInfo userInfo = loginUtil.getLoginUser();
		List<UserBinding> userBindings = new ArrayList<UserBinding>();
		int total = 0;
		PublishInfo publishInfo = new PublishInfo();
		if(userInfo != null){
			publishInfo.setUserInfo(userInfo);
			userBindings = userBindingService.findUserBindsByUserId(userInfo.getId());
			total = publishInfoService.publishCount(publishInfo);
		}
		ModelAndView m = new ModelAndView();
		m.getModelMap().put("total", total);
		m.getModelMap().put("userBindings", userBindings);
		m.setViewName("/publish/publish");
		return m;
	}
	
	
	
	/**
	 * 发布信息
	 * @author 黄莹璐
	 * @date: 2014-9-7-上午12:13:25
	 * //TODO  黄莹璐编辑
	 * @param info
	 * @return
	 */
	@RequestMapping(value="/publishInfo",method=RequestMethod.POST)
	@ResponseBody
	public ModelAndView publishInfo(String info){
		ModelAndView modelAndView = new ModelAndView();
		String accessToken = "2.00hIUQXB0228dO930a0a564du9JrLD";
		Timeline tm = new Timeline(accessToken);
		try {
			Status updateStatus = tm.updateStatus(info);
		} catch (WeiboException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return modelAndView;
		
	}
	
	@RequestMapping(value="/getBindingUser",method=RequestMethod.GET)
	@ResponseBody
	public ModelMap getBindingUser(BindingType bindingType){
		ModelMap modelMap = new ModelMap();
		UserInfo userInfo = loginUtil.getLoginUser();
		UserBinding userBinding = null;
		List<User> users = null;
		if(userInfo != null){
			userBinding = userBindingService.findUserBindsByUserIdAndType(userInfo.getId(), bindingType);
			String uid = "";
			String access_token = "";
			if(userBinding != null){
				switch (bindingType) {
				case BINDING_SINA_WEIBO:
					uid = userBinding.getBindId();
					access_token = userBinding.getAccessToken();
					friendships.setAccess_token(access_token);
					try {
						UserWapper userWapper = friendships.getFriendsByID(uid);
						users = userWapper.getUsers();
					} catch (WeiboException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					break;
				case BINDING_TENCENT_WEIBO:
					access_token = userBinding.getAccessToken();
					friendships.setAccess_token(access_token);
					try {
						UserWapper userWapper = friendships.getFriendsByID(uid);
						users = userWapper.getUsers();
					} catch (WeiboException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					break;
				default:
					break;
				}
			}
		}
		modelMap.put("users", users);
		modelMap.put("userBinding", userBinding);
		return modelMap;
	}
	
	/**
	 * 菜单信息
	 * @author 黄莹璐
	 * @date: 2014-9-7-上午12:13:39
	 * //TODO  黄莹璐编辑
	 * @return
	 */
	@RequestMapping(value="/menus",method=RequestMethod.GET)
	@ResponseBody
	public ModelMap getMenus(){
		ModelMap modelMap = new ModelMap();
		List<SysMenu> menus = sysMenuService.getMenus();
		modelMap.put("menus",menus);
		return modelMap;
	}
	
	/**
	 * 授权回调
	 * @author 黄莹璐
	 * @date: 2014-9-7-上午12:14:03
	 * //TODO  黄莹璐编辑
	 * @param code
	 * @return
	 */
	@RequestMapping(value="/oauthCallBack",method=RequestMethod.GET)
	@ResponseBody
	public ModelAndView oauthCallBack(String code,BindingType bindingType,String openid,String openkey){
		ModelAndView modelAndView = new ModelAndView();
		if(StringUtils.isNotBlank(code)){
			UserInfo loginUser = loginUtil.getLoginUser();
			AccessToken accessToken = null;
			String tokenId = null;
			String uid = null;
			switch (bindingType) {
			case BINDING_SINA_WEIBO:
				try {
					accessToken = oauth.getAccessTokenByCode(code);
					tokenId = accessToken.getAccessToken();
					uid = accessToken.getUid();
				} catch (WeiboException e2) {
					// TODO Auto-generated catch block
					e2.printStackTrace();
				}
				users.setAccess_token(tokenId);
				User user = null;
				try {
					user = users.showUserById(uid);
					Log.logInfo(user.toString());
				} catch (WeiboException e) {
					e.printStackTrace();
				}
				BindingList bindingList = bindingListService.loadByBindingType(bindingType);
				
				UserBinding userBinding = new UserBinding();
				userBinding.setBindId(uid);
				userBinding.setAccessToken(tokenId);
				userBinding.setBindUserName(user.getName());
				userBinding.setUserInfo(loginUser);
				userBinding.setBindingList(bindingList);
				userBindingService.save(userBinding);
				modelAndView.getModelMap().put("accessToken", accessToken);
				break;
			case BINDING_TENCENT_WEIBO:
				try {
					
					String clientId = properties.getProperty("tencent_app_id");
					String clientSecret = properties.getProperty("tencent_app_key");
					String redirectUri = properties.getProperty("tencent_redirect_URI");
					OAuthV2 oAuthV2 = new OAuthV2(clientId, clientSecret, redirectUri);
					oAuthV2.setAuthorizeCode(code);
					oAuthV2.setOpenid(openid);
					oAuthV2.setOpenkey(openkey);
					OAuthV2Client oAuthV2Client = new OAuthV2Client();
					boolean isToken = oAuthV2Client.accessToken(oAuthV2);
					String access_Token = oAuthV2.getAccessToken();
					
					String oAuthVersion = oAuthV2.getOauthVersion();
//					FriendsAPI friendsAPI = new FriendsAPI(oAuthVersion);
//					String idollist = friendsAPI.idollist(oAuthV2, "json", "30", "0", "0");
					UserAPI userAPI= new UserAPI(oAuthVersion);
		            String userInfo = userAPI.info(oAuthV2, "json");
					
		            com.intelligencesoft.pss.org.json.JSONObject responseJsonObject;
		            com.intelligencesoft.pss.org.json.JSONObject dataJsonObject = null;
	                responseJsonObject= new com.intelligencesoft.pss.org.json.JSONObject(userInfo);
	                com.intelligencesoft.pss.org.json.JSONObject jsonObject = responseJsonObject.getJSONObject("data");
	                TencentUserInfoVo tencentUserInfoVo = new TencentUserInfoVo(jsonObject);
		            System.out.println(uid);
		        	BindingList tencent_bindingList = bindingListService.loadByBindingType(bindingType);
					UserBinding tencent_binding = new UserBinding();
					tencent_binding.setBindId(uid);
					tencent_binding.setAccessToken(access_Token);
					tencent_binding.setBindUserName(tencentUserInfoVo.getName()); 
					tencent_binding.setUserInfo(loginUser);
					tencent_binding.setBindingList(tencent_bindingList);
					tencent_binding.setOpenId(openid);
					tencent_binding.setOpenKey(openkey);
					userBindingService.save(tencent_binding);
					modelAndView.getModelMap().put("accessToken", accessToken);
					System.out.println(userInfo);
				} catch (Exception e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
				break;
			default:
				break;
			}
		}else{
			
		}
		
		modelAndView.setViewName("redirect:showBindingList");
		return modelAndView;
	}
}
